package org.jeecg.modules.basic.print.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.print.entity.*;
import org.jeecg.modules.basic.print.service.IPrintConfigService;
import org.jeecg.modules.basic.print.service.IWmsDocumentTypeFieldsService;
import org.jeecg.modules.basic.print.service.IWmsDocumentTypeStatusService;
import org.jeecg.modules.basic.print.service.IWmsMaterialFieldsService;
import org.jeecg.modules.basic.print.vo.PrintConfigPage;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 打印配置
 * @Author: jeecg-boot
 * @Date: 2023-09-13
 * @Version: V1.0
 */
@Api(tags = "打印配置")
@RestController
@RequestMapping("/print/printConfig")
@Slf4j
public class PrintConfigController {
    @Autowired
    private IPrintConfigService printConfigService;
    @Autowired
    private IWmsDocumentTypeFieldsService wmsDocumentTypeFieldsService;
    @Autowired
    private IWmsDocumentTypeStatusService wmsDocumentTypeStatusService;
    @Autowired
    private IWmsMaterialFieldsService wmsMaterialFieldsService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IWmsMaterialFieldsService iWmsMaterialFieldsService;

    /**
     * 分页列表查询
     *
     * @param printConfig
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "打印配置-分页列表查询")
    @ApiOperation(value = "打印配置-分页列表查询", notes = "打印配置-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<PrintConfig>> queryPageList(PrintConfig printConfig,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<PrintConfig> queryWrapper = QueryGenerator.initQueryWrapper(printConfig, req.getParameterMap());
        Page<PrintConfig> page = new Page<PrintConfig>(pageNo, pageSize);
        IPage<PrintConfig> pageList = printConfigService.page(page, queryWrapper);
        for (PrintConfig record : pageList.getRecords()) {
            record.setDocumentTypeValue(sysDictService.queryDictTextByKey(record.getBusinessType(), record.getDocumentType()));
        }
        return Result.OK(pageList);
    }

    /**
     * 查询明细
     *
     * @param businessType
     * @param documentType
     * @return
     */
    @ApiOperation(value = "打印配置-查询明细", notes = "打印配置-根据业务类型查询明细")
    @GetMapping(value = "/detail")
    public Result<PrintConfigPage> queryPageList(@RequestParam(name = "businessType") String businessType,
                                                 @RequestParam(name = "documentType") String documentType) {
        LambdaQueryWrapper<PrintConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PrintConfig::getBusinessType, businessType)
                .eq(PrintConfig::getDocumentType, documentType);
        List<PrintConfig> pageList = printConfigService.list(queryWrapper);
        PrintConfigPage printConfigPage = new PrintConfigPage();
        if (pageList != null && pageList.size() > 0) {
            PrintConfig record = pageList.get(0);
            BeanUtils.copyProperties(record, printConfigPage);
            List<WmsDocumentTypeFields> wmsDocumentTypeFieldsList = wmsDocumentTypeFieldsService.selectByMainId(record.getId());
            printConfigPage.setWmsDocumentTypeFieldsList(wmsDocumentTypeFieldsList);
//			 List<WmsDocumentTypeStatus> wmsDocumentTypeStatusList = wmsDocumentTypeStatusService.selectByMainId(record.getId());
//			 printConfigPage.setWmsDocumentTypeStatusList(wmsDocumentTypeStatusList);
            List<WmsMaterialFields> wmsMaterialFieldsList = wmsMaterialFieldsService.selectByMainId(record.getId());
            printConfigPage.setWmsMaterialFieldsList(wmsMaterialFieldsList);
        }
        return Result.OK(printConfigPage);
    }

    /**
     * 添加
     *
     * @param printConfigPage
     * @return
     */
    @AutoLog(value = "打印配置-添加")
    @ApiOperation(value = "打印配置-添加", notes = "打印配置-添加")
    @RequiresPermissions("flow:print_config:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody PrintConfigPage printConfigPage) {
        PrintConfig printConfig = new PrintConfig();
        BeanUtils.copyProperties(printConfigPage, printConfig);
        printConfigService.saveMain(printConfig, printConfigPage.getWmsDocumentTypeFieldsList(), printConfigPage.getWmsDocumentTypeStatusList(), printConfigPage.getWmsMaterialFieldsList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param printConfigPage
     * @return
     */
    @AutoLog(value = "打印配置-编辑")
    @ApiOperation(value = "打印配置-编辑", notes = "打印配置-编辑")
    @RequiresPermissions("flow:print_config:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody PrintConfigPage printConfigPage) {
        PrintConfig printConfig = new PrintConfig();
        BeanUtils.copyProperties(printConfigPage, printConfig);
        PrintConfig printConfigEntity = printConfigService.getById(printConfig.getId());
        if (printConfigEntity == null) {
            return Result.error("未找到对应数据");
        }
        printConfigService.updateMain(printConfig, printConfigPage.getWmsDocumentTypeFieldsList(), printConfigPage.getWmsDocumentTypeStatusList(), printConfigPage.getWmsMaterialFieldsList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "打印配置-通过id删除")
    @ApiOperation(value = "打印配置-通过id删除", notes = "打印配置-通过id删除")
    @RequiresPermissions("flow:print_config:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        printConfigService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "打印配置-批量删除")
    @ApiOperation(value = "打印配置-批量删除", notes = "打印配置-批量删除")
    @RequiresPermissions("flow:print_config:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.printConfigService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "打印配置-通过id查询")
    @ApiOperation(value = "打印配置-通过id查询", notes = "打印配置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<PrintConfig> queryById(@RequestParam(name = "id", required = true) String id) {
        PrintConfig printConfig = printConfigService.getById(id);
        if (printConfig == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(printConfig);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "字段配置通过主表ID查询")
    @ApiOperation(value = "字段配置主表ID查询", notes = "字段配置-通主表ID查询")
    @GetMapping(value = "/queryWmsDocumentTypeFieldsByMainId")
    public Result<List<WmsDocumentTypeFields>> queryWmsDocumentTypeFieldsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<WmsDocumentTypeFields> wmsDocumentTypeFieldsList = wmsDocumentTypeFieldsService.selectByMainId(id);
        return Result.OK(wmsDocumentTypeFieldsList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "状态配置通过主表ID查询")
    @ApiOperation(value = "状态配置主表ID查询", notes = "状态配置-通主表ID查询")
    @GetMapping(value = "/queryWmsDocumentTypeStatusByMainId")
    public Result<List<WmsDocumentTypeStatus>> queryWmsDocumentTypeStatusListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<WmsDocumentTypeStatus> wmsDocumentTypeStatusList = wmsDocumentTypeStatusService.selectByMainId(id);
        return Result.OK(wmsDocumentTypeStatusList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "表体物料字段配置通过主表ID查询")
    @ApiOperation(value = "表体物料字段配置主表ID查询", notes = "表体物料字段配置-通主表ID查询")
    @GetMapping(value = "/queryWmsMaterialFieldsByMainId")
    public Result<List<WmsMaterialFields>> queryWmsMaterialFieldsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<WmsMaterialFields> wmsMaterialFieldsList = wmsMaterialFieldsService.selectByMainId(id);
        return Result.OK(wmsMaterialFieldsList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param printConfig
     */
    @RequiresPermissions("flow:print_config:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PrintConfig printConfig) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<PrintConfig> queryWrapper = QueryGenerator.initQueryWrapper(printConfig, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<PrintConfig> printConfigList = printConfigService.list(queryWrapper);

        // Step.3 组装pageList
        List<PrintConfigPage> pageList = new ArrayList<PrintConfigPage>();
        for (PrintConfig main : printConfigList) {
            PrintConfigPage vo = new PrintConfigPage();
            BeanUtils.copyProperties(main, vo);
            List<WmsDocumentTypeFields> wmsDocumentTypeFieldsList = wmsDocumentTypeFieldsService.selectByMainId(main.getId());
            vo.setWmsDocumentTypeFieldsList(wmsDocumentTypeFieldsList);
            List<WmsDocumentTypeStatus> wmsDocumentTypeStatusList = wmsDocumentTypeStatusService.selectByMainId(main.getId());
            vo.setWmsDocumentTypeStatusList(wmsDocumentTypeStatusList);
            List<WmsMaterialFields> wmsMaterialFieldsList = wmsMaterialFieldsService.selectByMainId(main.getId());
            vo.setWmsMaterialFieldsList(wmsMaterialFieldsList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "打印配置列表");
        mv.addObject(NormalExcelConstants.CLASS, PrintConfigPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("打印配置数据", "导出人:" + sysUser.getRealname(), "打印配置"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("flow:print_config:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<PrintConfigPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PrintConfigPage.class, params);
                for (PrintConfigPage page : list) {
                    PrintConfig po = new PrintConfig();
                    BeanUtils.copyProperties(page, po);
                    printConfigService.saveMain(po, page.getWmsDocumentTypeFieldsList(), page.getWmsDocumentTypeStatusList(), page.getWmsMaterialFieldsList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 查看打印地址列表
     *
     * @return
     */
    @AutoLog(value = "查看打印地址列表")
    @ApiOperation(value = "查看打印地址列表", notes = "查看打印地址列表")
    @GetMapping(value = "/getPrintShowInfo")
    public Result<List<PrintShowDTO>> getPrintShowInfo() {
        List<PrintShowDTO> printShowInfoes = printConfigService.getPrintShowInfo();
        return Result.OK(printShowInfoes);
    }
    /**
     * 单据类型下拉
     *
     * @return
     */
    @AutoLog(value = "单据类型下拉")
    @ApiOperation(value = "单据类型下拉", notes = "单据类型下拉")
    @GetMapping(value = "/getConfigList")
    public Result<List<ConfigListItemVO>> getConfigList(@RequestParam("businessType") Integer businessType) {
        List<ConfigListItemVO> res = new ArrayList<>();
        LambdaQueryWrapper<PrintConfig> queryWrapper = new LambdaQueryWrapper<>();
        String items = "";
        //入库
        if (1 == businessType){
            queryWrapper.eq(PrintConfig::getBusinessType,"document_task");
            items = "document_task";
        }
        //出库
        if (2 == businessType){
            queryWrapper.eq(PrintConfig::getBusinessType,"outbound_task");
            items = "outbound_task";
        }
        //移库
        if (3 == businessType){
            queryWrapper.eq(PrintConfig::getBusinessType,"move_type");
            items = "move_type";
        }
        //查询启用的
        queryWrapper.eq(PrintConfig::getStatus,"0");
        List<PrintConfig> configs = printConfigService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(configs)){
            List<String> collect = configs.stream().map(PrintConfig::getDocumentType).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)){
                List<DictModel> dictItems = sysDictService.getDictItems(items);
                for (PrintConfig config : configs) {
                    for (DictModel dictItem : dictItems) {
                        if (config.getDocumentType().equals(dictItem.getValue())){
                            ConfigListItemVO vo = new ConfigListItemVO();
                            vo.setValue(config.getDocumentType());
                            vo.setText(dictItem.getText());
                            vo.setLabel(dictItem.getLabel());
                            vo.setTitle(dictItem.getTitle());
                            res.add(vo);
                            break;
                        }
                    }
                }
            }
        }
        return Result.OK(res);
    }
    /**
     * 批量设置字段显隐
     *
     * @return
     */
    @AutoLog(value = "批量设置字段显隐")
    @ApiOperation(value = "批量设置字段显隐", notes = "批量设置字段显隐")
    @GetMapping(value = "/setFieldsHidden")
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> setFieldsHidden(String businessType,String fieldsCode, Integer hidden) {
        List<PrintConfig> configList = printConfigService.list(new LambdaQueryWrapper<PrintConfig>()
                .eq(PrintConfig::getBusinessType, businessType)
        );
        List<String> list = configList.stream().map(PrintConfig::getId).collect(Collectors.toList());
        wmsDocumentTypeFieldsService.update(new LambdaUpdateWrapper<WmsDocumentTypeFields>()
                .set(WmsDocumentTypeFields::getHidden,hidden)
                .in(WmsDocumentTypeFields::getPrintConfigId,list)
                .eq(WmsDocumentTypeFields::getCode,fieldsCode)
        );
        iWmsMaterialFieldsService.update(new LambdaUpdateWrapper<WmsMaterialFields>()
                .set(WmsMaterialFields::getHidden,hidden)
                .in(WmsMaterialFields::getPrintConfigId,list)
                .eq(WmsMaterialFields::getCode,fieldsCode));
        return Result.OK();
    }
}
